package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdUtil;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UpdaterRedisLock;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdUtil redisIdUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    /**
     * 优惠券秒杀
     *
     * @param voucherId
     * @return
     */
    @Override
    @Transactional
    public Result seckillVoucher(Long voucherId) {
        // 1.判断优惠券秒杀是否在规定时间内
        // 1.1.查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        // 1.2.判断优惠券是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())){
            return Result.fail("秒杀尚未开始！");
        }
        // 1.3.判断优惠券是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束！");
        }
        // 2.判断优惠券库存是否充足
        if (voucher.getStock()<1){
            return Result.fail("库存不足");
        }
        // 3.一人一单
        // 3.1.手动编写Redis分布式锁解决并发下重复下单问题
        Long userId = UserHolder.getUser().getId();
        // UpdaterRedisLock lock = new UpdaterRedisLock("order:" + userId, stringRedisTemplate);
        // boolean isLock = lock.tryLock(1200);

        // 3.1.使用Redisson分布式锁解决并发下重复下单问题
        RLock redissonLock = redissonClient.getLock("order:" + userId);
        boolean isLock = redissonLock.tryLock();
        if (!isLock){
            // 获取锁失败，不可重复下单，返回错误！
            return Result.fail("不允许重复下单！");
        }
        try {
            // 3.2.判断用户是否已经购买过该优惠券
            int count = query().eq("user_id", userId)
                    .eq("voucher_id", voucherId)
                    .count();
            if (count > 0) {
                // 用户已经购买过该优惠券
                return Result.fail("用户已购买");
            }
            // 4.扣减库存
            boolean flag = seckillVoucherService.update()
                    .setSql("stock = stock - 1")
                    .eq("voucher_id", voucherId)
                    .gt("stock",0) // 乐观锁，CAS 法，防止超卖
                    .update();
            if (!flag){
                return Result.fail("库存不足");
            }
            // 5.创建优惠券秒杀订单
            VoucherOrder voucherOrder = new VoucherOrder();
            // 5.1.设置订单ID
            long orderId = redisIdUtil.nextId("order");
            voucherOrder.setId(orderId);
            // 5.2.设置用户Id
            voucherOrder.setUserId(userId);
            // 5.3.设置优惠券Id
            voucherOrder.setVoucherId(voucherId);
            // 5.4.DB
            boolean isSave = save(voucherOrder);
            if (!isSave){
                throw new RuntimeException("创建订单失败");
            }
            // 6.返回订单Id
            return Result.ok(orderId);
        } finally {
            // 7.释放锁
            redissonLock.unlock();
        }
        /* // 3.扣减优惠券库存
        boolean flag = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("vocher_id", voucherId)
                .gt("stock",0) // 乐观锁，CAS 法
                .update();
        // 4.判断优惠券库存扣减是否成功
        if (!flag){
            return Result.fail("库存不足");
        }
        // 5.创建优惠券秒杀订单
        VoucherOrder voucherOrder = new VoucherOrder();
        // 5.1.设置订单ID
        long orderId = redisIdUtil.nextId("order");
        voucherOrder.setId(orderId);
        // 5.2.设置用户Id
        Long userId = UserHolder.getUser().getId();
        voucherOrder.setUserId(userId);
        // 5.3.设置优惠券Id
        voucherOrder.setVoucherId(voucherId);
        // 5.4.DB
        save(voucherOrder);
        // 6.返回订单Id
        return Result.ok(orderId); */
    }
    /**
     * 创建订单
     *
     * @param userId
     * @param voucherId
     * @return
     */
    @Transactional
    public Result createVoucherOrder(Long userId, Long voucherId) {
//        synchronized (userId.toString().intern()) {
        // 1、判断当前用户是否是第一单
        int count = this.count(new LambdaQueryWrapper<VoucherOrder>()
                .eq(VoucherOrder::getUserId, userId));
        if (count >= 1) {
            // 当前用户不是第一单
            return Result.fail("用户已购买");
        }
        // 2、用户是第一单，可以下单，秒杀券库存数量减一
        boolean flag = seckillVoucherService.update(new LambdaUpdateWrapper<SeckillVoucher>()
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .gt(SeckillVoucher::getStock, 0)
                .setSql("stock = stock -1"));
        if (!flag) {
            throw new RuntimeException("秒杀券扣减失败");
        }
        // 3、创建对应的订单，并保存到数据库
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdUtil.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);
        flag = this.save(voucherOrder);
        if (!flag) {
            throw new RuntimeException("创建秒杀券订单失败");
        }
        // 4、返回订单id
        return Result.ok(orderId);
    }
}
